<?php
define('DIRTREE', 0);
define('ARRAYTREE', 1);


function treelist( $type, $object, $prefile, $checked=array() )
/*
Gör en fin kataloglistning med dess kataloger (om $showdir == true) och filer (om $showfiles == true).
Kräver dirlist_next i 'public/ajax.php'
$prefile anger vilken sträng postvariablerna över ikryssade filer ska börja med
*/
{
	$_SESSION['ajax_dirlist'][$prefile]['type'] = $type;
	$_SESSION['ajax_dirlist'][$prefile]['object'] = $object;
	$_SESSION['ajax_dirlist'][$prefile]['checked'] = $checked;

	echo '
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!-- Hide script from old browsers

function checkbox_mark_'.$prefile.'( id )
{
	id = "'.$prefile.'" + id;
	var reg_sub = new RegExp("^"+escape(id)+"/");

	var el, i = 0;
	while (el = document.pageform.elements[i++]) {
		escaped_id = escape(el.id);
		if( escaped_id.match(reg_sub) ) {
			if( document.getElementById( id ).checked ) {
				el.checked = true;
				el.disabled = true;
			}
		}
	}
}

function showdir_'.$prefile.'( xmlHttp, id )
{
	//Skriv ut svaret
	document.getElementById( id + "_subdir" ).innerHTML = xmlHttp.responseText;

	checkbox_mark_'.$prefile.'( id );

	var re = new RegExp(/<script\b.*?>([\s\S]*?)<\//ig);
	var match;
	while (match = re.exec(xmlHttp.responseText)) {
		eval(match[1]);
	}
}

function openclosedir_'.$prefile.'( id )
{
	var str = document.getElementById( id + "_cross" ).style.backgroundImage;
        if( document.getElementById( id + "_subdir" ).style.display == "none" ) {
                document.getElementById( id + "_subdir" ).innerHTML = "Laddar...";
                document.getElementById( id + "_subdirline" ).style.display = "";
                document.getElementById( id + "_subdir" ).style.display = "";
		ajax_send(\'ajax.php\', \'jsfunc\', showdir_'.$prefile.', \'ajax_dirlist^'.$prefile.'^\'+id, id);
		if( document && document.getElementById( id + "_img" ) )
                	document.getElementById( id + "_img" ).src = "/images/folder_open.gif";
		document.getElementById( id + "_cross" ).style.backgroundImage = str.replace(/plus/, "minus");
        }
        else {
                document.getElementById( id + "_subdir" ).innerHTML = "";
                document.getElementById( id + "_subdirline" ).style.display = "none";
                document.getElementById( id + "_subdir" ).style.display = "none";
		if( document && document.getElementById( id + "_img" ) )
                	document.getElementById( id + "_img" ).src = "/images/folder_closed.gif";
		document.getElementById( id + "_cross" ).style.backgroundImage = str.replace(/minus/, "plus");
        }
}

function checkbox_click_'.$prefile.'( id ) {
	prefile_id = "'.$prefile.'" + id;

	checkstat = document.getElementById( prefile_id ).checked;
	if( checkstat == true )
		ajax_send("ajax.php", "htmlid", "foot", \'ajax_dirlist_add^'.$prefile.'^\'+id);
	else
		ajax_send("ajax.php", "htmlid", "foot", \'ajax_dirlist_del^'.$prefile.'^\'+id);

	var el, i = 0;
	while (el = document.pageform.elements[i++]) {
		var reg = new RegExp("^"+escape(prefile_id)+"/");
		escaped_id = escape(el.id);
		if( escaped_id.match(reg) ) {
			el.checked = checkstat;
			el.disabled = checkstat;
		}
	}
}

// End hiding script from old browsers -->
</SCRIPT>
	';
	treetrlist( $type, $object, $prefile, $checked );
}


function treelist_next( )
/*
ska ligga under 'public/ajax.php' om dirlist används.
*/
{
	header("Content-Type: text/html;charset=UTF-8");

	$arr = explode('^', $_GET['msg']);
        if( isset($arr[1]) ) {
            $prefile = $arr[1];

            //avbryt om ej variabler i session
            if( isset($_SESSION['ajax_dirlist'][$prefile]['object']) ) {
                    switch( $arr[0] ) {
                    case 'ajax_dirlist':
                            $type = $_SESSION['ajax_dirlist'][$prefile]['type'];
                            $dir = $_SESSION['ajax_dirlist'][$prefile]['object'];
                            $checked = $_SESSION['ajax_dirlist'][$prefile]['checked'];

                            if( $type == DIRTREE ) {
                                    $newdir = realpath( $arr[2] );
                                    if( $newdir == false || ! is_dir($newdir) ) {
                                            echo "katalogen finns inte";
                                            exit;
                                    }
                                    $legal_path = false;
                                    if( ! @is_array($object) )
                                            @$object = array( $object );
                                    foreach( $object AS $dir ) {
                                            if( preg_match('#^'.addslashes($dir).'#', $newdir) ) {
                                                    $legal_path = true;
                                                    break;
                                            }
                                    }
                                    if( ! $legal_path ) {
                                            echo "utanför tillåten sökväg";
                                            exit;
                                    }
                            }
                            else
                                    $newdir = $arr[2];

                            treetrlist( $type, $newdir.'/', $prefile, $checked );
                            break;
                    case 'ajax_dirlist_add':
                            $type = $_SESSION['ajax_dirlist'][$prefile]['type'];
                            $dir = $_SESSION['ajax_dirlist'][$prefile]['dir'];
                            $checked = $_SESSION['ajax_dirlist'][$prefile]['checked'];
                            $newcheck = false;

                            if( $type == DIRTREE ) {
                                    $newcheck = realpath( $arr[2] );
                                    // kontrollera att det är en katalog och ligger inom tillåten avgränsning
                                    if( $newcheck === false || !preg_match('#^'.preg_quote($dir).'#', $arr[2]) || in_array($newcheck, $checked) ) {
                                            exit;
                                    }
                            }
                            else if( !in_array($arr[2], $checked) )
                                    $newcheck = $arr[2];
                            if( $newcheck !== false ) {
                                    //radera underliggande markeringar
                                    $wants_uncheck = preg_grep('#^'.preg_quote($newcheck).'/#', $checked);
                                    foreach( $wants_uncheck AS $key => $name )
                                            unset( $_SESSION['ajax_dirlist'][$prefile]['checked'][ $key ]);
                                    //lägg till markering
                                    $_SESSION['ajax_dirlist'][$prefile]['checked'][] = $newcheck;
                            }
                            break;
                    case 'ajax_dirlist_del':
                            $type = $_SESSION['ajax_dirlist'][$prefile]['type'];
                            $checked = $_SESSION['ajax_dirlist'][$prefile]['checked'];
                            $newcheck = false;

                            if( $type == DIRTREE ) {
                                    if( realpath($arr[2]) )
                                            $newcheck = realpath($arr[2]);
                            }
                            else
                                    $newcheck = $arr[2];

                            if( $newcheck !== false ) {
                                    $key = array_search($newcheck, $checked);
                                    if( $key !== false ) {
                                            unset( $_SESSION['ajax_dirlist'][$prefile]['checked'][ $key ]);
                                    }
                            }
                            break;
                    }
            }
        }
}

function treetrlist( $type, $object, $prefile, $checked )
/*
Ritar ut kataloginnehåll i form av tabell
*/
{
	$filetypes = array( 
		'doc' => 'doc_word.gif',
		'xls' => 'doc_excel.gif'
	);

	$havefiles = false;

	echo '<table cellspacing="0" cellpadding="0">';
	if( $type == DIRTREE ) {
		if( is_array($object) ) {
			foreach( $object AS $path ) {
				if( preg_match('#^/home/?$#', $path ) )
					$filenames[] = array(true, '/', 'home', 'Hemkataloger');
				else if( preg_match('#^/var/shares/?$#', $path ) )
					$filenames[] = array(true, '/var/', 'shares', 'Fildelningar');
				else {
					$arr = preg_match('#^(.*/)(.+?)/?$#', $path, $matches );
					$filenames[] = array(true, $matches[1], $matches[2]);
				}
			}
		}
		else {
			$dir = $object;
			$filenames = array();

			$dh  = @opendir($dir);
			if( $dh === false ) {
				echo 'Fel vid öppning';
				echo '</table>';
				return;
			}
			while (false !== ($filename = readdir($dh))) {
				if( isset($path) AND preg_match('#^/home/?$#', $path ) )
					$filenames[] = array(true, '/', 'home', 'Hemkataloger');
				else if( isset($path) AND preg_match('#^/var/shares/?$#', $path ) )
					$filenames[] = array(true, '/var/', 'shares', 'Fildelningar');
				else
					$filenames[] = array(is_dir($dir.$filename), $dir, $filename);
			}
		}
	}
// ARRAYTREE
	else {
		$tree = $_SESSION['ajax_dirlist'][$prefile]['object'];
		foreach( $tree AS $path ) {
			if( is_array($object) )
				$object = "";
			if( ($object=="" && preg_match('#^var/shares$#', $path )) || preg_match('#^'.preg_quote($object).'[^/]+$#', $path ) ) {
				if( preg_match('#^home$#', $path) )
					$filenames[] = array(true, '', 'home', 'Hemkataloger');
				else if( preg_match('#^var/shares$#', $path ) )
					$filenames[] = array(true, 'var/', 'shares', 'Fildelningar');
				else {
					$arr = preg_match('#^(.*?)([^/]+)$#', $path, $matches );
					$isdir = preg_grep ( '#^'.preg_quote($matches[1].$matches[2]).'/#', $tree );
					$filenames[] = array($isdir, $matches[1], $matches[2]);
				}
			}
		}
	}

	$i = 0;
	if( is_array($filenames) ) {
		foreach( $filenames AS $arrnr => $filearr ) {
			$isdir = $filearr[0];
			$dir = $filearr[1];
			$filename = $filearr[2];
			//Alias på fil / katalog
			if( isset($filearr[3]) )
				$filealias = $filearr[3];
			else
				$filealias = $filename;

			if( $filename != '.' && $filename != '..' ) {
				$i++;

				$check = false;
				$open = false;
				foreach( $checked AS $testline ) {
					if( preg_match('#^'.preg_quote($dir.$filename).'$#i', $testline) ) {
						$check = true;
						break;
					}
					else if( preg_match('#^'.preg_quote($dir.$filename).'#i', $testline) ) {
						$open = true;
						break;
					}
				}

				//Är katalog
				if( $isdir ) {
					  //Sista
					if( $arrnr == end(array_keys($filenames)) ) {
						$line_pic = '/images/blank.gif';
						$cross_pic = '/images/tree/img-corner-plus.gif';
						$cross_repeat ='no-repeat';
					}
					else {
						$line_pic = '/images/tree/img-line.gif';
						$cross_pic = '/images/tree/img-tcorner-plus.gif';
						$cross_repeat ='repeat-y';
					}
					$cross_extra = 'onClick="javascript:openclosedir_'.$prefile.'(\''.$dir.$filename.'\')"';
					$cross_style = 'cursor: pointer;';
					$checkbox_extra = 'onClick="javascript:checkbox_click_'.$prefile.'(\''.$dir.$filename.'\')"';
					$ftype_pic = '/images/folder_closed.gif';
				}
				//Är fil
				else {
					  //Sista
					if( $arrnr == end(array_keys($filenames)) ) {
						$cross_pic = '/images/tree/img-corner.gif';
						$cross_repeat ='no-repeat';
					}
					else {
						$cross_pic = '/images/tree/img-tcorner.gif';
						$cross_repeat ='repeat-y';
					}
					$cross_extra = '';
					$cross_style = '';
					$checkbox_extra = 'onClick="javascript:checkbox_click_'.$prefile.'(\''.$dir.$filename.'\')"';
					  //bild för filen
					if( preg_match('/\.([a-z0-9]+)$/i', $filename, $match ) && array_key_exists( $match[1], $filetypes ) )
						$ftype_pic = '/images/'.$filetypes[ $match[1] ];
					else
						$ftype_pic = '/images/doc_general.gif';
				}

				echo '<tr>';
				  //bild för prickad korsning
				echo   '<td id="'.$dir.$filename.'_cross" style="background-image:url(\''.$cross_pic.'\');background-repeat:'.$cross_repeat.';width:16px;margin:0px;padding:0px;'.$cross_style.'" '.$cross_extra.'>&nbsp;&nbsp;&nbsp;</td>';
				  //checkbox
				echo   '<td style="width:16px"><input type="checkbox" id="'.$prefile.$dir.$filename.'" '.$checkbox_extra.' ';
				if( $check )
					echo 'checked';
				echo    '></td><td style="text-align:left;width:100%;font-size:0.8em;">';
				  //bild på fil / katalog
				if( $type == DIRTREE )
					echo   '<img src="'.$ftype_pic.'" id="'.$dir.$filename.'_img">';
				  //filnamn
				echo    '&nbsp;'.str_replace(' ', '&nbsp;', $filealias).'</td>';
				echo '</tr>';

				  //underkatalog
				if( $isdir ) {
					echo '<tr>';
					echo   '<td id="'.$dir.$filename.'_subdirline" style="background-image:url(\''.$line_pic.'\');background-repeat:repeat-y;display:none">&nbsp;</td>';
					echo   '<td id="'.$dir.$filename.'_subdir" style="display:none" colspan=4></td>';
					echo '</tr>';
					if( $open ) {
				        	echo '
<script type="text/javascript">
openclosedir_'.$prefile.'(\''.$dir.$filename.'\');
</script>
						';
					}
				}
				$havefiles = true;
				
			}
		}
	}
	if( $havefiles == false ) {
		echo "<tr><td>inga filer eller kataloger</td></tr>";
	}
	echo '</table>';
}


?>
